import Login from '../pages/login/index';
import Layout from '../pages/layout/index';
import Home from '../pages/home/index';
import Other from '../pages/other/index';
import NotPage from '../pages/404/index';
import { useRoutes, Navigate } from 'react-router-dom'

const routers = [
  {
    path: '/login',
    element: <Login></Login>
  },
  {
    path: '/',
    element: <Layout></Layout>,
    children: [
      {
        path: '/',
        element: <Home></Home>,
      },
      {
        path: '/other',
        element: <Other></Other>,
      },
    ]
  },
  {
    path: '*',
    element: <NotPage></NotPage>
  },
]

const isUserAuthenticated = () => {
  const token = localStorage.getItem('token')
  return token && token.length > 0
}

const AuthRoute = ({ children }) => {
  if (!isUserAuthenticated()) {
    return (
      <div>
        {children}
        <Navigate to='/login'/>
      </div>
    )
  }
  return (<div>{children}</div>)
}

export default (props) => {
  const routerEls = useRoutes(routers)
  return (
    <AuthRoute>
      { routerEls }
    </AuthRoute>
  )
}